<script lang="ts" setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import qs from 'qs'
import { GetTuangouTuanDeta, PatchTuanModifyType } from '@/api/modules/tuangou'
import GetCacheData from '@/store/modules/NewPageCache'

const imgDomain = 'https://img1.eprhan.cc'
const route = useRoute()
const router = useRouter()
const cacheData = GetCacheData()

// 查询表单
const findFrom = reactive({
  ...(cacheData.GetCacheData('tuangouTuan').fromData),
})

const dataList: any = reactive({
  list: [],
})

let PageNum = 1
const loading = ref(true)
const total = ref(0)

async function GetDataList(PageIndex: number = 1, PageSize: number = 20) {
  const params = {
    PageIndex,
    PageSize,
    ...(findFrom.TuanLeaderId && { TuanLeaderId: findFrom.TuanLeaderId }),
    ...(findFrom.ProductId && { ProductId: findFrom.ProductId }),
    ...(findFrom.TuanTitle && { TuanTitle: findFrom.TuanTitle }),
    ...(findFrom.Enable !== '~' && { Enable: findFrom.Enable }),
  }
  const parameter = qs.stringify(params)
  await GetTuangouTuanDeta(parameter).then(async (dataRes: any) => {
    if (dataRes.succeeded) {
      dataList.list = dataRes.data.items
      total.value = dataRes.data.total
      loading.value = false
    }
    else {
      ElMessage.error(`查询失败。${dataRes.errors}`)
      loading.value = false
    }
  })
    .catch(() => {
      loading.value = false
    })
  loading.value = false
}

// 查询
function Inquire() {
  GetDataList(1, cacheData.GetCacheData('tuangouTuan').currentSize)
  cacheData.SetCacheData('tuangouTuan', PageNum, cacheData.GetCacheData('tuangouTuan').currentSize, findFrom.value)
}

// 修改状态
function ModifyType(params: any) {
  PatchTuanModifyType(params).then((res: any) => {
    if (res.statusCode === 200) {
      ElMessage.success('修改成功')
      // GetDataList(PageNum, PageSize)
    }
    else {
      ElMessage.error(`修改失败${res.errors}`)
    }
  })
}

// 添加
function AddData() {
  if (route.query.tuanLeaderId) {
    router.push({
      name: 'tuangouTuanDetail',
      query: {
        tuanLeaderId: route.query.tuanLeaderId,
      },
    })
  }
  else {
    router.push({
      name: 'tuangouTuanDetail',
    })
  }
}
// 浏览记录
function ViewPage() {
  router.push({
    name: 'tuangouTuanViewLIst',
  })
}
// 编辑
function EditData(id: number) {
  if (route.query.tuanLeaderId) {
    router.push({
      name: 'tuangouTuanDetail',
      query: {
        id,
        tuanLeaderId: route.query.tuanLeaderId,
      },
    })
  }
  else {
    router.push({
      name: 'tuangouTuanDetail',
      query: {
        id,
      },
    })
  }
}

// 图片预览
const srcList = ref([])

function handlePreview(row: any) {
  srcList.value = (row.coverPic.split(',')).map((url: string) => imgDomain + url)
}

// 翻页
function handleSizeChange(val: number) {
  GetDataList(1, val)
  cacheData.SetCacheData('tuangouTuan', PageNum, val)
}
function handleCurrentChange(val: number) {
  GetDataList(val, cacheData.GetCacheData('tuangouTuan').currentSize)
  cacheData.SetCacheData('tuangouTuan', val, cacheData.GetCacheData('tuangouTuan').currentSize)
  PageNum = val
}

const nowPageNum = computed(() => {
  return cacheData.GetCacheData('tuangouTuan').currentPage || 1
})

onMounted(async () => {
  if (route.query.tuanLeaderId) {
    findFrom.TuanLeaderId = route.query.tuanLeaderId
    Inquire()
  }
  else {
    GetDataList(PageNum, cacheData.GetCacheData('tuangouTuan').currentSize)
  }
})
</script>

<template>
  <div>
    <PageMain>
      <SearchBar :show-toggle="false">
        <div class="header">
          <el-form label-positio="right" label-width="auto">
            <div class="from">
              <el-form-item label="团长ID">
                <el-input v-model="findFrom.TuanLeaderId" placeholder="请输入团长ID" clearable @keyup.enter="Inquire" />
              </el-form-item>
              <el-form-item label="商品ID">
                <el-input v-model="findFrom.ProductId" placeholder="请输入商品ID" clearable @keyup.enter="Inquire" />
              </el-form-item>
              <el-form-item label="是否可用">
                <el-select v-model="findFrom.Enable" placeholder="请选择状态">
                  <el-option label="全部" value="~" />
                  <el-option label="可用" :value="true" />
                  <el-option label="停用" :value="false" />
                </el-select>
              </el-form-item>
            </div>
          </el-form>
          <div class="text-right">
            <el-button @click="Inquire">
              查询
            </el-button>
          </div>
        </div>
      </SearchBar>
      <ElDivider border-style="dashed" />
      <div class="mb-5 text-right">
        <el-button type="success" @click="AddData">
          添加
        </el-button>
        <el-button @click="ViewPage">
          浏览记录
        </el-button>
      </div>
      <el-table v-loading="loading" :data="dataList.list" stripe style="width: 100%;" border>
        <el-table-column align="center" prop="tuanLeaderId" label="团长ID" width="100" />
        <el-table-column align="center" prop="leaderName" label="团长" width="140" />
        <el-table-column align="center" prop="tuanInfoId" label="团购信息ID" width="100" />
        <el-table-column align="center" prop="productId" label="商品ID" width="100" />
        <el-table-column align="center" prop="productName" label="商品名称" width="100" />
        <el-table-column align="center" prop="productPic" label="商品图片" width="100">
          <template #default="scope">
            <el-avatar shape="square" :size="60" :src="imgDomain + scope.row.productPic" />
          </template>
        </el-table-column>
        <el-table-column align="center" prop="banner" label="banner图" width="100">
          <template #default="scope">
            <el-avatar shape="square" :size="60" :src="imgDomain + scope.row.banner" />
          </template>
        </el-table-column>
        <el-table-column align="center" prop="detailPic" label="图文详情" width="100">
          <template #default="scope">
            <el-avatar shape="square" :size="60" :src="imgDomain + scope.row.detailPic" />
          </template>
        </el-table-column>
        <el-table-column align="center" prop="viewCon" label="浏览人数" width="100" />
        <el-table-column align="center" prop="shareImg" label="分享图" width="100">
          <template #default="scope">
            <el-avatar shape="square" :size="60" :src="imgDomain + scope.row.shareImg" />
          </template>
        </el-table-column>
        <el-table-column header-align="center" width="300" prop="shareTxt" label="分享语" />
        <el-table-column header-align="center" width="480" prop="tuanDesp" label="团购简介" />
        <el-table-column align="center" width="200" prop="pubTime" label="上架时间" />
        <el-table-column align="center" width="200" prop="endTime" label="结束时间" />
        <el-table-column align="center" prop="coverPic" label="封面图片" min-width="350">
          <template #default="scope">
            <el-scrollbar>
              <div class="scrollbar-flex-content">
                <el-image
                  v-for="(item, index) in scope.row.coverPic.split(',')"
                  :key="index"
                  class="scrollbar-flex-img"
                  :src="imgDomain + item"
                  :preview-src-list="srcList"
                  :initial-index="index"
                  :preview-teleported="true"
                  @click="handlePreview(scope.row)"
                />
              </div>
            </el-scrollbar>
          </template>
        </el-table-column>
        <el-table-column align="center" width="200" prop="addTime" label="添加时间" />
        <el-table-column align="center" width="200" prop="updateTime" label="更新时间" />
        <el-table-column align="center" label="状态" fixed="right" width="180">
          <template #default="scope">
            <el-switch
              v-model="scope.row.enable"
              active-text="启用"
              inactive-text="停用"
              @change="ModifyType({ id: scope.row.tuanInfoId, enable: scope.row.enable })"
            />
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" fixed="right" min-width="150">
          <template #default="scope">
            <el-button type="primary" @click="EditData(scope.row.tuanInfoId)">
              编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="height: 10px;" />
      <el-pagination
        :default-page-size="cacheData.GetCacheData('tuangouTuan').currentSize"
        :page-sizes="[5, 10, 20, 50, 100]"
        layout="total, sizes, ->, prev, pager, next, jumper"
        :total="total"
        :default-current-page="nowPageNum"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </PageMain>
  </div>
</template>

<style scoped>
.header {
  display: grid;
  grid-template-columns: 6fr 1fr;

  .from {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    grid-gap: 20px;

    .el-form-item {
      margin-bottom: 0;
    }
  }

  @media screen and (width <= 500px) {
    .from {
      grid-template-columns: repeat(auto-fill, minmax(30vw, 1fr));
    }
  }
}

.scrollbar-flex-content {
  display: flex;
  max-width: 300px;

  .scrollbar-flex-img {
    display: flex;
    flex-shrink: 0;
    align-items: center;
    justify-content: center;
    width: auto;
    height: 60px;
    margin-right: 10px;
  }
}
</style>
